package com.example.nick.bodyapplication.xml

import android.util.Log
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler

class SaxHelper : DefaultHandler() {
    private var person: Person? = null
    var persons: ArrayList<Person>? = null

    //当前解析的元素标签
    private var tagName: String? = null

    override fun startDocument() {
//        super.startDocument()
        this.persons = ArrayList<Person>()
        Log.i("xml", "sax xml startDocument")
    }

    override fun startElement(
        uri: String?,
        localName: String?,
        qName: String?,
        attributes: Attributes?
    ) {
//        super.startElement(uri, localName, qName, attributes)
        if (localName.equals("person")) {
            person = Person()
            person!!.id = attributes!!.getValue("id").toInt()
            Log.i("xml", "开始处理person元素~")
        }
        tagName = localName
        Log.i("xml", "sax xml startElement $tagName")
    }

    override fun characters(ch: CharArray?, start: Int, length: Int) {
//        super.characters(ch, start, length)
        //判断当前标签是否有效
        //判断当前标签是否有效
        if (tagName != null) {
            val data = String(ch!!, start, length)
            //读取标签中的内容
            if (tagName == "name") {
                person!!.name = data
                Log.i("xml", "处理name元素内容")
            } else if (tagName == "age") {
                person!!.age = data.toInt()
                Log.i("xml", "处理age元素内容")
            }
        }
        Log.i("xml", "sax xml characters")
    }

    override fun endElement(uri: String?, localName: String?, qName: String?) {
//        super.endElement(uri, localName, qName)
        if (localName.equals("person")) {
            person?.let { this.persons?.add(it) }
            person = null
            Log.i("xml", "处理person元素结束~")
        }
        this.tagName = null
        Log.i("xml", "sax xml endElement")
    }

    override fun endDocument() {
//        super.endDocument()
        Log.i("xml", "sax xml endDocument")
    }

}